package com.linkage.jz.bankruptcy.fragment.Vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteEditVoteActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteEditVoteNewActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteMyVoteResultActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteMyVote;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

public class ProVoteGroupInfoFragment extends ProVoteBaseFragment implements View.OnClickListener {

    private static final String ARG_PARAM_VOTE_ID = "arg_param_vote_id";
    private static final String ARG_PARAM_CREDITOR_ID = "arg_param_creditor_id";

    private String voteId;
    private String creditorId;

    private View rootView;
    private LRecyclerView mRecyclerView;
    private LRecyclerViewAdapter mAdapter;
    private VoteGroupAdapter mDataAdapter;
    private List<ProVoteMyVote> mData;

    public static ProVoteGroupInfoFragment newInstance(String voteId, String creditorId) {
        ProVoteGroupInfoFragment fragment = new ProVoteGroupInfoFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM_VOTE_ID, voteId);
        args.putSerializable(ARG_PARAM_CREDITOR_ID, creditorId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        voteId = getArguments().getString(ARG_PARAM_VOTE_ID, "");
        creditorId = getArguments().getString(ARG_PARAM_CREDITOR_ID, "");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_pro_vote_detai_groupinfo, container, false);
        }
        mRecyclerView = rootView.findViewById(R.id.list);
        mData = new ArrayList<>();
        mDataAdapter = new VoteGroupAdapter(mData);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader); //设置下拉刷新Progress的样式
        mRecyclerView.setArrowImageView(com.github.jdsjlzx.R.drawable.progressbar);  //设置下拉刷新箭头
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        mAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ProVoteMyVote item = mData.get(position);
                if(item.isVote()) {
                    Intent intent = ProVoteMyVoteResultActivity.start(getActivity(), item.getGroupId(), item.getVoteOpinion(), item.getSupplementOpinion(), item.isAllowChange());
                    startActivity(intent);
                }else {
//                    Intent intent = new Intent(getActivity(), ProVoteEditVoteActivity.class);
//                    intent.putExtra("vote", false);
//                    intent.putExtra("voteId", voteId);
//                    intent.putExtra("groupId", item.getGroupId());
//                    intent.putExtra("allowChange", item.isAllowChange());
//                    startActivityForResult(intent, ProVoteEditVoteNewActivity.REQUEST_CODE_VOTE);
                    ProVoteEditVoteNewActivity.start(getActivity(),mData,item);
                    getActivity().finish();
                }
            }
        });

        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchMyVote();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.forceToRefresh();
        return rootView;
    }

    class VoteGroupAdapter extends BaseRecyclerAdapter<BaseHolder> {

        List<ProVoteMyVote> list;

        public VoteGroupAdapter(List<ProVoteMyVote> data) {
            this.list = data;
        }

        @NonNull
        @Override
        public VoteGroupAdapter.VoteGroupViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new VoteGroupAdapter.VoteGroupViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_pro_vote_detail_item_group, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(@NonNull BaseHolder viewHolder, int i) {
            VoteGroupAdapter.VoteGroupViewHolder holder = (VoteGroupAdapter.VoteGroupViewHolder)viewHolder;
            ProVoteMyVote item = list.get(i);
            holder.groupNameText.setText(item.getGroupName());
            holder.groupVoteStatus.setText(item.isVote() ? "已表决" : "待表决");
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        class VoteGroupViewHolder extends BaseHolder {
            TextView groupNameText;
            TextView groupVoteStatus;
            public VoteGroupViewHolder(@NonNull View itemView) {
                super(itemView);
                groupNameText = itemView.findViewById(R.id.item_group_name);
                groupVoteStatus = itemView.findViewById(R.id.item_group_vote_status);
            }
        }
    }

    private void fetchMyVote() {
        showLoading();
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .getVoteMyVote_Creditor(userToken, voteId, creditorId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        mRecyclerView.refreshComplete(1000);
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        boolean grouped = json.getAsJsonObject("data").get("grouped").getAsBoolean();
                        try {
                            if(grouped) {
                                JsonArray data = json.getAsJsonObject("data").getAsJsonArray("info");
                                List<ProVoteMyVote> myVoteList = ProVoteMyVote.parse(data);
                                mData.clear();
                                mData.addAll(myVoteList);
                            }else {
                                JsonObject data = json.getAsJsonObject("data").getAsJsonObject("info");
                                List<ProVoteMyVote> myVoteList = new ArrayList<>();
                                if(data != null) {
                                    myVoteList.add(ProVoteMyVote.parse(data));
                                }
                                mData.clear();
                                mData.addAll(myVoteList);
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            mRecyclerView.refreshComplete(10000);
                            mDataAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mRecyclerView.refreshComplete(1000);
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mRecyclerView.refreshComplete(1000);
                        hideLoading();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ProVoteEditVoteActivity.REQUEST_CODE_VOTE && resultCode == RESULT_OK) {
            getActivity().setResult(RESULT_OK);
            getActivity().finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }
}
